package com.qfedu.common.neo4j.utils;

import com.qfedu.common.neo4j.node.InviteShip;
import com.qfedu.common.neo4j.node.UserNode;
import org.neo4j.driver.QueryRunner;
import org.neo4j.driver.Record;
import org.neo4j.driver.Result;
import org.springframework.data.neo4j.core.Neo4jClient;
import org.springframework.data.neo4j.core.Neo4jTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @Classname Neo4jUtils
 * @Description TODO
 * @Date 2025-05-27 11:07
 * @Created by 老任与码
 */
@Component
public class Neo4jUtils {

    @Resource
    private Neo4jTemplate neo4jTemplate;

    @Resource
    private Neo4jClient neo4jClient;

    public UserNode getUserNode(Integer id) {
        // 将节点的子节点、子节点的子节点都一起查询出来
//        Optional<UserNode> byId = neo4jTemplate.findById(id, UserNode.class);
//        return byId.orElse(null);

        String cql = "match(u:User{id:$id}) return u";
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        Optional<UserNode> one = neo4jTemplate.findOne(cql, map, UserNode.class);
        return one.orElse(null);
    }

    public void addNode(UserNode pnode) {
        neo4jTemplate.save(pnode);
    }

    public void addNode(UserNode pnode, UserNode cnode) {
        InviteShip inviteShip = new InviteShip();
        inviteShip.setTargetUserNode(cnode);
        pnode.getInviteShips().add(inviteShip);
        neo4jTemplate.save(pnode);
    }

    public Map<String, Object> findMapById(Integer id) {
        // COLLECT() 将数据转为列表
        // apoc.convert.toTree 是存储过程，使用call 调用，函数使用return调用
        // 针对存储过程，通过YIELD获取指定名称的执行结果
        String cql = "MATCH p = (n:User {id: $id})-[:INVITE*]->(m:User)\n" +
                "WITH COLLECT(p) AS paths\n" +
                "CALL apoc.convert.toTree(paths) YIELD value\n" +
                "RETURN value";
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);

        QueryRunner queryRunner = neo4jClient.getQueryRunner();
        Result run = queryRunner.run(cql, map);
        // 结果集中只有一条记录，使用single()返回Record对象，如果有多条记录，使用list()
        Record single = run.single();
        Map<String, Object> map1 = single.get("value").asMap();
        System.out.println(map1);
        return map1;
    }
}
